/*
 * @Author: zhangyang
 * @Date: 2020-12-08 11:26:10
 * @LastEditTime: 2022-02-27 15:00:34
 * @Description: HTTP 网络请求模块
 */
import axios from 'axios';
import { ElLoadingService } from 'element-plus';
import { getToken, removeToken } from '../store';
import { USE_REAL_SERVER } from '../store';

import type { Method } from 'axios';
import type { YoungModule } from '../types';

let BASE_URL = import.meta.env.VITE_BASE_HTTP;
let mode = import.meta.env.MODE;
const arr = mode.split('.');
if (arr[1]) {
  BASE_URL = `${BASE_URL}/${arr[0]}`;
}
/**
 * 请求真实服务器
 */
if (USE_REAL_SERVER.value) {
  BASE_URL = import.meta.env.VITE_PI_HTTP;
}

/**
 * 创建 Axios 实例
 */
const net = axios.create({
  baseURL: BASE_URL,
  timeout: 1000 * 5
});


type ParamsObj = Record<string, any>;

/**
 * 不需要 token 的请求，默认 post 请求
 */
export const requestWithoutToken = (param: ParamsObj, method: Method = 'post') => {
  const data = new FormData();
  for (const [key, value] of Object.entries(param)) {
    data.append(key, value);
  }
  return net({
    method: 'post',
    data
  });
};

/**
 * 需要 token 的普通请求
 */
export const basicRequest = (param: ParamsObj) => {
  const { token, aid } = getToken();
  param['token'] = token;
  param['aid'] = aid;
  return requestWithoutToken(param);
};
/**
 * 文件上传
 */
export const upload = (param: ParamsObj, formData: FormData) => {
  const { token, aid } = getToken();
  param['token'] = token;
  param['aid'] = aid;
  for (const [key, value] of Object.entries(param)) {
    formData.append(key, value);
  }
  return net({
    method: 'post',
    data: formData
  });
};

export const install: YoungModule = (app) => {
  let loading: any;
  const startLoading = () => {
    loading = ElLoadingService({
      lock: true,
      text: '拼命加载中...',
      background: 'rgb(255, 255, 255, 0)'
    });
  };
  const endLoading = () => loading.close();

  /**
   * 设置请求拦截器
   */
  net.interceptors.request.use((req) => {
    startLoading();
    return req;
  }, (error) => {
    console.error(error);
    ElMessage.error(error);
    return Promise.reject(error);
  });

  enum Status {
    TOKEN_NO_USE = -1,
    OK = 0
  };

  interface ResponseObj {
    status: number;
    data: any;
    msg: string;
  };

  /**
   * 设置响应拦截器
   */
  net.interceptors.response.use((response) => {
    endLoading();
    const res = response.data as ResponseObj;
    if (res.status === Status.OK) {
      return res.data;
    } else if (res.status === Status.TOKEN_NO_USE) {
      // 登录过期
      removeToken();
      location.reload();
    } else {
      const ErrMsg = res.msg;
      ElMessage.error(ErrMsg);
      throw new Error(ErrMsg);
    }
  }, (error: Error) => {
    endLoading();
    console.error(error);
    ElMessage.error(error.message);
    throw new Error(error.message);
  });
};
